package com.temp.controller.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.temp.dto.EditCampaignDTO;
import com.temp.dto.SearchCampaignDTO;
import com.temp.entity.Campaign;
import com.temp.entity.User;
import com.temp.enumeration.CampaignStatus;
import com.temp.result.Result;
import com.temp.service.CampaignService;
import com.temp.service.SystemSettingService;
import com.temp.utils.RandomBigDecimalGenerator;
import com.temp.utils.ShiroUtils;
import com.temp.utils.StringUtils;
import com.temp.vo.CampaignStatusVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/campaign")
@Api(tags = "活动相关接口")
@Slf4j
@Validated
public class CampaignController {

    @Autowired
    private CampaignService campaignService;

    @Autowired
    private SystemSettingService settingService;

    @PostMapping("/edit")
    @ApiOperation("编辑活动")
    @RequiresPermissions("user:campaign:edit")
    public Result editCampaign(@Valid @RequestBody EditCampaignDTO campaignDTO) {
        log.info("编辑活动的信息:{}", campaignDTO);
        BigDecimal goalAmount = campaignDTO.getGoalAmount();
        Optional<BigDecimal> max_amount = settingService.getSettingValue("max_amount", BigDecimal.class);
        Optional<BigDecimal> min_amount = settingService.getSettingValue("min_amount", BigDecimal.class);
        RandomBigDecimalGenerator.validateAmount(goalAmount, min_amount, max_amount);
        User user = ShiroUtils.getUser();
        Campaign campaign = new Campaign();
        if (CampaignStatus.WAIT.equals(campaignDTO.getStatus()) && StringUtils.isNull(campaignDTO.getId())) {
            Integer allNotEndedCampaign = campaignService.findAllNotEndedCampaign(user.getId());
            if (allNotEndedCampaign > 0) {
                return Result.error("apiMsg.hadReapCampaign");
            }
            Optional<BigDecimal> min_robot_process = settingService.getSettingValue("min_robot_process", BigDecimal.class);
            Optional<BigDecimal> max_robot_process = settingService.getSettingValue("max_robot_process", BigDecimal.class);
            BigDecimal randomValue = RandomBigDecimalGenerator.getRandomBetween(min_robot_process, max_robot_process);
            campaign.setRobotDonationProcess(randomValue.intValue());
        }
        BeanUtils.copyProperties(campaignDTO, campaign);
        campaign.setUserId(user.getId());
        campaign.setProgress(null);
        campaign.setStatus(campaignDTO.getStatus().getValue());
        return campaignService.saveOrUpdate(campaign)
                ? Result.success("apiMsg.optionSuccess")
                : Result.error("apiMsg.optionError");
    }

    @PostMapping("/explore")
    @ApiOperation("探索的数据")
    @RequiresPermissions("user:campaign:explore")
    public Result explore(@RequestBody SearchCampaignDTO campaignDTO) {
        campaignDTO.formatParam();
        campaignDTO.setStatus(CampaignStatus.ACTIVE.getValue());
        campaignDTO.setVisibility("0");
        List<CampaignStatusVO> list = campaignService.findCampaignByStatus(campaignDTO);
        return Result.success(list, "apiMsg.querySuccess");
    }

    @GetMapping("/random")
    @ApiOperation("获取主页随机的活动")
    public Result getRandomCampaign() {
        SearchCampaignDTO searchCampaignDTO = new SearchCampaignDTO();
        searchCampaignDTO.setPage(1);
        searchCampaignDTO.setPageSize(3);
        searchCampaignDTO.setCondition("2");
        searchCampaignDTO.setStatus(CampaignStatus.ACTIVE.getValue());
        searchCampaignDTO.setVisibility("0");
        List<CampaignStatusVO> list = campaignService.findCampaignByStatus(searchCampaignDTO);
        return Result.success(list, "apiMsg.querySuccess");
    }

    @PostMapping("/ownStatus")
    @ApiOperation("获取状态的活动")
    @RequiresPermissions("user:campaign:ownStatus")
    public Result onStatus(@RequestBody SearchCampaignDTO campaignDTO) {
        User user = ShiroUtils.getUser();
        campaignDTO.formatParam();
        campaignDTO.setUserId(user.getId());
        List<CampaignStatusVO> list = campaignService.findCampaignByStatus(campaignDTO);
        return Result.success(list, "apiMsg.querySuccess");
    }

    @GetMapping("/campaignById")
    @ApiOperation("获取id对应的活动")
    @RequiresPermissions("user:campaign:campaignById")
    public Result getById(@NotNull(message = "apiMsg.IdNotNull") @RequestParam("id") Long id) {
        CampaignStatusVO campaign = campaignService.findCampaignById(id);
        return StringUtils.isNotNull(campaign)
                ? Result.success(campaign, "apiMsg.querySuccess")
                : Result.error("apiMsg.queryError");
    }

    @GetMapping("/data")
    @ApiOperation("统计用户活动筹款信息")
    @RequiresPermissions("user:campaign:data")
    public Result getCampaignData() {
        User user = ShiroUtils.getUser();
        Map<String, Object> data = campaignService.findCampaignDataByUserId(user.getId());
        return Result.success(data,"apiMsg.querySuccess");
    }

    @GetMapping("/toDraft")
    @ApiOperation("用户修改活动")
    @RequiresPermissions("user:campaign:toDraft")
    public Result campaignToDraft(@NotNull(message = "apiMsg.IdNotNull") @RequestParam Long campaignId) {
        boolean isSuccess = campaignService.update(Wrappers.<Campaign>lambdaUpdate()
                .eq(Campaign::getId, campaignId)
                .set(Campaign::getStatus, CampaignStatus.DRAFT.getValue()));
        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }
}
